﻿@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>资产入库管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="~/Scripts/layui/css/layui.css" rel="stylesheet" />
    <style>
        body {
            background-color: #f2f2f2;
            margin: 0;
            padding: 0;
        }

        .container {
            padding: 15px;
        }

        .search-form {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
        }

        .table-container {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
            padding: 15px;
        }

        .operation-btns .layui-btn {
            margin-right: 5px;
        }

        .header {
            background: #fff;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
        }

        .header-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .layui-form-label {
            width: 100px;
        }

        .layui-input-block {
            margin-left: 130px;
        }
    </style>
</head>
<body>
    <!-- 顶部标题栏 -->
    <div class="header">
        <div class="layui-row">
            <div class="layui-col-md6">
                <span class="header-title">资产入库管理</span>
            </div>
        </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-form">
            <form class="layui-form" id="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">资产名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="AssetName" placeholder="输入资产名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">入库人员</label>
                        <div class="layui-input-inline">
                            <input type="text" name="EmpolyName" placeholder="输入入库人员" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">资产类型</label>
                        <div class="layui-input-inline">
                            <select name="AssetType">
                                <option value="">全部</option>
                                <option value="1">固定资产</option>
                                <option value="2">办公用品</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="button" class="layui-btn layui-btn-normal" id="btnSearch">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                    </div>
                    <div class="layui-inline" style="float: right;">
                        <button type="button" class="layui-btn layui-btn-warm" id="btnAdd">
                            <i class="layui-icon layui-icon-add-1"></i> 资产入库
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-container">
            <table class="layui-table" id="assetPutTable" lay-filter="assetPutTable"></table>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="operationTpl">
        <div class="operation-btns">
            <button class="layui-btn layui-btn-xs layui-btn-normal" lay-event="edit">
                <i class="layui-icon layui-icon-edit"></i> 修改
            </button>
        </div>
    </script>

    <!-- 资产类型列模板 -->
    <script type="text/html" id="assetTypeTpl">
        {{# if(d.AssetTypeID == 1){ }}
        <span class="layui-badge layui-bg-blue">固定资产</span>
        {{# } else if(d.AssetTypeID == 2){ }}
        <span class="layui-badge layui-bg-green">办公用品</span>
        {{# } else { }}
        <span class="layui-badge">其他</span>
        {{# } }}
    </script>

    <!-- 入库表单模板 -->
    <script type="text/html" id="putFormTpl">
        <form class="layui-form" id="assetPutForm" style="padding: 20px;">
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>资产名称</label>
                <div class="layui-input-block">
                    <select name="AssetID" id="assetSelect" lay-verify="required" lay-search>
                        <option value="">请选择资产</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>入库数量</label>
                <div class="layui-input-block">
                    <input type="number" name="AssetPutCount" lay-verify="required|number" placeholder="请输入入库数量" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>入库人员</label>
                <div class="layui-input-block">
                    <select name="EmpolyID" id="empolySelect" lay-verify="required" lay-search>
                        <option value="">请选择入库人员</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>入库日期</label>
                <div class="layui-input-block">
                    <input type="text" name="AssetPutDate" id="putDate" lay-verify="required" placeholder="请选择入库日期" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="AssetPutReMark" placeholder="请输入备注信息" class="layui-textarea" rows="3"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formSubmit">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </script>

    <!-- 修改表单模板 -->
    <script type="text/html" id="editFormTpl">
        <form class="layui-form" id="assetEditForm" style="padding: 20px;">
            <input type="hidden" name="AssetID" value="{{ d.AssetID }}">
            <input type="hidden" name="EmpolyID" value="{{ d.EmpolyID }}">
            <div class="layui-form-item">
                <label class="layui-form-label">资产名称</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" value="{{ d.AssetName }}" disabled style="background-color: #f8f8f8;">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>入库数量</label>
                <div class="layui-input-block">
                    <input type="number" name="AssetPutCount" value="{{ d.AssetPutCount }}" lay-verify="required|number" placeholder="请输入入库数量" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red">*</span>入库日期</label>
                <div class="layui-input-block">
                    <input type="text" name="AssetPutDate" lay-verify="required" placeholder="请选择入库日期" autocomplete="off" class="layui-input layui-date-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="AssetPutReMark" placeholder="请输入备注信息" class="layui-textarea" rows="3">{{ d.AssetPutReMark || '' }}</textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="editFormSubmit">提交</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                </div>
            </div>
        </form>
    </script>

    <script src="~/Scripts/layui/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'laydate', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var $ = layui.$;

            // 日期格式化
            function formatDate(date) {
                if (!date) return '';
                try {
                    // 如果是字符串格式的日期
                    if (typeof date === 'string') {
                        // 处理 /Date(timestamp)/ 格式
                        if (date.startsWith('/Date(')) {
                            var timestamp = parseInt(date.match(/\d+/)[0]);
                            date = new Date(timestamp);
                        } else {
                            date = new Date(date);
                        }
                    }
                    // 如果是 Date 对象
                    if (date instanceof Date && !isNaN(date.getTime())) {
                        return date.getFullYear() + '-' +
                            (date.getMonth() + 1).toString().padStart(2, '0') + '-' +
                            date.getDate().toString().padStart(2, '0');
                    }

                    return '';
                } catch (e) {
                    console.error('日期格式化错误:', e);
                    return '';
                }
            }

            // 初始化日期控件
            laydate.render({
                elem: '#putDate',
                type: 'date',
                value: new Date()
            });

            // 初始化表格 - 简化parseData逻辑
            var tableIns = table.render({
                elem: '#assetPutTable',
                url: '/AssetPut/GetAssetPutList',
                page: true,
                cols: [[
                    { field: 'AssetPutID', title: '编号', width: 80, sort: true },
                    { field: 'AssetName', title: '资产名称', width: 150 },
                    {
                        field: 'AssetTypeID',
                        title: '资产类别',
                        width: 120,
                        templet: '#assetTypeTpl'
                    },
                    { field: 'AssetPutCount', title: '入库数量', width: 100, sort: true },
                    { field: 'EmpolyName', title: '入库人员', width: 120 },
                    {
                        field: 'AssetPutDate',
                        title: '入库日期',
                        width: 120,
                        sort: true,
                        templet: function (d) {
                            return formatDate(d.AssetPutDate);
                        }
                    },
                    { field: 'AssetPutReMark', title: '备注', minWidth: 150 },
                    {
                        title: '操作',
                        width: 100,
                        align: 'center',
                        toolbar: '#operationTpl'
                    }
                ]],
                parseData: function (res) {
                    console.log('原始接口返回数据:', res);

                    // 根据实际返回的数据结构调整
                    if (res.Code === 200) {
                        // 解析分页数据结构: { Code: 200, Data: { Total: 0, Items: [] }, Message: "成功" }
                        var dataList = res.Data && res.Data.Items ? res.Data.Items : [];
                        var totalCount = res.Data && res.Data.Total ? res.Data.Total : 0;

                        console.log('解析后的数据:', dataList);
                        console.log('数据总数:', totalCount);

                        return {
                            "code": 0, // layui表格要求code为0表示成功
                            "msg": res.Message || '',
                            "count": totalCount,
                            "data": dataList
                        };
                    } else {
                        return {
                            "code": res.Code || -1,
                            "msg": res.Message || '获取数据失败',
                            "count": 0,
                            "data": []
                        };
                    }
                },
                text: {
                    none: '暂无入库记录数据'
                },
                error: function (xhr, type, error) {
                    console.error('表格加载错误:', error);
                    layer.msg('数据加载失败: ' + error);
                }
            });

            // 搜索按钮事件
            $('#btnSearch').on('click', function () {
                var formData = $('#searchForm').serializeArray();
                var searchParams = {};

                $.each(formData, function () {
                    if (this.value) {
                        searchParams[this.name] = this.value;
                    }
                });

                console.log('搜索参数:', searchParams);

                tableIns.reload({
                    where: searchParams,
                    page: { curr: 1 }
                });
            });

            // 资产入库按钮事件
            $('#btnAdd').on('click', function () {
                openPutForm();
            });

            // 表格工具条事件
            table.on('tool(assetPutTable)', function (obj) {
                var data = obj.data;

                if (obj.event === 'edit') {
                    openEditForm(data);
                }
            });

            // 打开新增入库表单
            function openPutForm() {
                var layerIndex = layer.open({
                    type: 1,
                    title: '资产入库',
                    area: ['500px', '450px'],
                    content: $('#putFormTpl').html(),
                    success: function (layero, index) {
                        // 设置默认日期为今天
                        var today = new Date();
                        var dateString = today.getFullYear() + '-' +
                            (today.getMonth() + 1).toString().padStart(2, '0') + '-' +
                            today.getDate().toString().padStart(2, '0');

                        // 手动设置日期值
                        layero.find('#putDate').val(dateString);

                        // 初始化日期控件
                        laydate.render({
                            elem: layero.find('#putDate')[0],
                            type: 'date',
                            value: today,
                            format: 'yyyy-MM-dd'
                        });

                        // 加载资产下拉框
                        loadAssetSelect();

                        // 加载员工下拉框
                        loadEmpolySelect();

                        // 重新渲染表单
                        form.render();

                        // 表单提交事件
                        form.on('submit(formSubmit)', function (data) {
                            // 确保日期有值
                            if (!data.field.AssetPutDate) {
                                data.field.AssetPutDate = dateString;
                            }
                            submitForm(data.field, null, layerIndex);
                            return false;
                        });
                    }
                });
            }


            // 打开修改表单
            function openEditForm(data) {
                console.log('修改数据:', data);

                // 使用 laytpl 渲染模板
                var getTpl = document.getElementById('editFormTpl').innerHTML;
                var content = layui.laytpl(getTpl).render({
                    d: data
                });

                var layerIndex = layer.open({
                    type: 1,
                    title: '修改入库记录',
                    area: ['500px', '400px'],
                    content: content,
                    success: function (layero, index) {
                        // 设置日期值
                        var formattedDate = formatDate(data.AssetPutDate);
                        layero.find('input[name="AssetPutDate"]').val(formattedDate);

                        // 初始化日期控件
                        laydate.render({
                            elem: layero.find('input[name="AssetPutDate"]')[0],
                            type: 'date',
                            format: 'yyyy-MM-dd',
                            value: formattedDate
                        });

                        // 重新渲染表单
                        form.render();

                        // 修改表单的提交事件 - 使用不同的filter名称
                        form.on('submit(editFormSubmit)', function (formData) {
                            submitForm(formData.field, data.AssetPutID, layerIndex);
                            return false;
                        });
                    },
                    end: function () {
                        // 清理工作
                        form.off('submit(editFormSubmit)');
                    }
                });
            }

            // 加载资产下拉框
            function loadAssetSelect() {
                $.ajax({
                    url: '/AssetPut/GetAssets',
                    type: 'GET',
                    success: function (res) {
                        console.log('资产下拉框数据:', res);
                        if (res.Code === 200) {
                            var html = '<option value="">请选择资产</option>';
                            $.each(res.Data, function (i, item) {
                                html += '<option value="' + item.AssetID + '">' + item.AssetName + '</option>';
                            });
                            $('#assetSelect').html(html);
                            form.render('select');
                        }
                    },
                    error: function (xhr, error) {
                        console.error('加载资产下拉框失败:', error);
                    }
                });
            }

            // 加载员工下拉框
            function loadEmpolySelect() {
                $.ajax({
                    url: '/AssetPut/GetEmpolys',
                    type: 'GET',
                    success: function (res) {
                        console.log('员工下拉框数据:', res);
                        if (res.Code === 200) {
                            var html = '<option value="">请选择入库人员</option>';
                            $.each(res.Data, function (i, item) {
                                html += '<option value="' + item.EmpolyID + '">' + item.EmpolyName + '</option>';
                            });
                            $('#empolySelect').html(html);
                            form.render('select');
                        }
                    },
                    error: function (xhr, error) {
                        console.error('加载员工下拉框失败:', error);
                    }
                });
            }
            // 提交表单
            function submitForm(formData, assetPutId, layerIndex) {
                var url = assetPutId ? '/AssetPut/UpdateAssetPut' : '/AssetPut/AddAssetPut';
                var method = assetPutId ? 'POST' : 'POST'; // 都使用 POST

                // 数据验证和格式化
                if (!validateFormData(formData, assetPutId)) {
                    return;
                }

                // 格式化数据
                var submitData = {};

                if (assetPutId) {
                    // 修改操作的数据结构 - 只提交可修改的字段
                    submitData = {
                        AssetPutID: parseInt(assetPutId),
                        AssetPutCount: parseInt(formData.AssetPutCount),
                        AssetPutReMark: formData.AssetPutReMark || ''
                    };

                    // 处理日期
                    if (formData.AssetPutDate) {
                        submitData.AssetPutDate = new Date(formData.AssetPutDate);
                    } else {
                        submitData.AssetPutDate = new Date();
                    }

                } else {
                    // 新增操作的数据结构
                    submitData = {
                        AssetID: parseInt(formData.AssetID),
                        AssetPutCount: parseInt(formData.AssetPutCount),
                        EmpolyID: parseInt(formData.EmpolyID),
                        AssetPutReMark: formData.AssetPutReMark || ''
                    };

                    // 处理日期
                    if (formData.AssetPutDate) {
                        submitData.AssetPutDate = new Date(formData.AssetPutDate);
                    } else {
                        submitData.AssetPutDate = new Date();
                    }
                }

                console.log('提交的数据:', submitData);
                console.log('请求URL:', url);
                console.log('请求方法:', method);

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function (res) {
                        if (res.Code === 200) {
                            layer.msg(res.Message, { icon: 1 });
                            layer.close(layerIndex);
                            tableIns.reload();
                        } else {
                            console.error('操作失败:', res);
                            layer.msg(res.Message || '操作失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, error) {
                        console.error('提交失败:', xhr.responseText);
                        var errorMsg = '操作失败，请检查网络连接或联系管理员';
                        try {
                            var errorResponse = JSON.parse(xhr.responseText);
                            errorMsg = errorResponse.Message || errorResponse.message || errorMsg;
                        } catch (e) {
                            // 如果不是JSON响应，显示原始错误
                            if (xhr.responseText) {
                                errorMsg = '服务器错误: ' + xhr.responseText.substring(0, 100);
                            }
                        }
                        layer.msg(errorMsg, { icon: 2 });
                    }
                });
            }
            // 表单数据验证
            function validateFormData(formData, assetPutId) {
                // 如果是修改操作，只验证可修改的字段
                if (assetPutId) {
                    // 修改时只验证入库数量、入库日期
                    if (!formData.AssetPutCount || formData.AssetPutCount <= 0) {
                        layer.msg('请输入有效的入库数量', { icon: 2 });
                        return false;
                    }
                    if (!formData.AssetPutDate) {
                        layer.msg('请选择入库日期', { icon: 2 });
                        return false;
                    }
                    return true;
                } else {
                    // 新增时需要验证所有字段
                    if (!formData.AssetID) {
                        layer.msg('请选择资产', { icon: 2 });
                        return false;
                    }
                    if (!formData.AssetPutCount || formData.AssetPutCount <= 0) {
                        layer.msg('请输入有效的入库数量', { icon: 2 });
                        return false;
                    }
                    if (!formData.EmpolyID) {
                        layer.msg('请选择入库人员', { icon: 2 });
                        return false;
                    }
                    if (!formData.AssetPutDate) {
                        layer.msg('请选择入库日期', { icon: 2 });
                        return false;
                    }
                    return true;
                }
            }


            // 表单重置
            form.on('reset(searchForm)', function (data) {
                tableIns.reload({
                    where: {},
                    page: { curr: 1 }
                });
            });
        });
    </script>
</body>
</html>